import axios, { type InternalAxiosRequestConfig, type AxiosResponse } from "axios";

import { getAccessToken } from "@/utils/auth";
import { ElMessage } from "element-plus";
// import router from "@/router";

const request = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL,
    timeout: 10000,
})

// 请求拦截器
request.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    const access_token = getAccessToken();
    if (config.headers.Authorization != "no-auth" && access_token) {
        console.log("request set access_token:", access_token);
        config.headers.Authorization = `Bearer ${access_token}`;
    }
    else {
        delete config.headers.Authorization;
    }
    return config;
},
    (error) => Promise.reject(error)
);

// 响应拦截器
request.interceptors.response.use((response: AxiosResponse) => {
    if (response.config.responseType === "blob") {
        return response;
    }

    const { code, message, data } = response.data;
    if (code == 200) {
        return data;
    }

    ElMessage.error(message || "请求失败");
    return Promise.reject(new Error(message || "Error"));
},
    async (error) => {
        console.log("request error", error);

        const { config, response } = error;

        return Promise.reject(error);
    }
)

export default request;